import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
import api from '@/api/module/list'

export function useCategory() {
  const { proxy } = getCurrentInstance()
  const tableLoading = ref(false);

  const tableRef = ref(null);
  const showPage = ref(true)

  const pageData = reactive({
    total: 0,//注意，element严格计算total数量，当total=0时，任何跳转page，都返回1
    page: 1,
    size: 10,
    list: [
      {
        uniId: 1,
        name: '模块名称',
        cat: '模块分类',
        status: '状态',
        sort: '排序',
        createTime: '创建时间',
        updateTime: '更新时间',
        remark: '备注'
      },
      {
        uniId: 2,
        name: '模块名称2',
        cat: '模块分类2',
        status: '状态2',
        sort: '排序2',
        createTime: '创建时间2',
        updateTime: '更新时间2',
        remark: '备注2'
      },
    ]
  });

  const searchFormRef = ref(null);
  const searchForm = reactive({
    name: '',//模块名称
    cat: '',//模块分类
    status: '',//状态 0隐藏 1显示
    sort: '',//排序
    createTime: '',//创建时间
  });

  //保存/详情modal---------start-------
  const drawerModalRef = ref(null)
  const formRef = ref(null)
  const modalTitle = ref('')

  const inputForm = reactive({
    uniId: '',
    name: '',//模块名称
    level: 0,//模块等级
    isShow: 1,//状态 0隐藏 1显示
    sort: 0,//排序
    parentId: 0,
    //TODO 有域名id关联参数，匹配id后，自动在该域名下新增一条分类,前端传入参数即可，目前定义relationId
  })
  const inputRules = {
    name: [
      { required: true, message: '请输入模块名称', trigger: 'blur' },
      { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
    ],
    level: [
      { required: true, message: '请输入模块等级', trigger: 'blur' },
      // { min: 1, max: 5, message: '长度在 1 到 5' },
      {
        validator: (rule, value, callback) => {
          if (!value && value != 0) {
            callback(new Error("请输入模块等级"));
          } else if (value && !proxy.$validator.isInteger(value)) {
            callback(new Error("模块等级必须为整数"));
          } else {
            callback();
          }
        }
      }
    ],
    isShow: [
      { required: true, message: '请选择状态', trigger: 'blur' },
    ],
    sort: [
      { required: true, message: '请输入排序', trigger: 'blur' },
      // { min: 1, max: 5, message: '长度在 1 到 5' },
      {
        validator: (rule, value, callback) => {
          if (!value && value != 0) {
            callback(new Error("请输入排序"));
          } else if (value && !proxy.$validator.isInteger(value)) {
            callback(new Error("排序必须为整数"));
          } else {
            callback();
          }
        }
      }
    ],
    parentId: [
      { required: true, message: '请选择父级', trigger: 'blur' },
    ],
  }
  const formLabelWidth = ref("100")
  const loadingModal = ref(false)

  function saveModal() {
    console.log("保存/详情: ", inputForm);
    formRef.value.validate(valid => {
      if (valid) {
        loadingModal.value = true;
        api.save(inputForm).then(res => {
          console.log("保存/详情响应: ", res);
          if (res.success) {
            proxy.$messageInfo.toast.success("保存成功");
            drawerModalRef.value.close();
            pageReset();
          } else {
            proxy.$messageInfo.notific.error(res.message);
          }

        }).catch((e) => {
          proxy.$messageInfo.notific.error(e);
        }).finally(() => {
          setTimeout(() => {
            loadingModal.value = false;
          }, 1000);
        })
      } else {
        proxy.$messageInfo.notific.error("请完善表单信息");
      }
    });
  }

  function getDetail(uniId) {
    loadingModal.value = true;
    api.detail(uniId).then(res => {
      console.log("详情响应: ", res);
      if (res.success) {
        resetForm(res.content);
        drawerModalRef.value.init();
      } else {
        proxy.$messageInfo.notific.error("参数异常，请重新操作");
      }

    }).catch((e) => {
      proxy.$messageInfo.notific.error(e);
    }).finally(() => {
      setTimeout(() => {
        loadingModal.value = false;
      })
    })
  }

  //保存/详情modal---------end-------

  //获取模块列表
  function getList() {
    tableLoading.value = true;
    console.log("模块列表请求: ", searchForm, tableLoading.value);
    api.page({
      page: pageData.page,
      size: pageData.size,
      name: searchForm.name,
      cat: searchForm.cat,
      status: searchForm.status,
      sort: searchForm.sort
    }).then(res => {
      console.log("模块列表响应: ", res);
      tableLoading.value = false;
      pageData.list = res.content.list;
      pageData.total = res.content.total;
      console.log("页面数据更新: ", pageData);
    }).catch((e) => {
      proxy.$messageInfo.notific.error(e);
    }).finally(() => {
      setTimeout(() => {
        tableLoading.value = false;
      }, 1000);
      // tableLoading.value = false;
    });
  }

  function pageSizeChange(val) {
    console.log(`每页 ${val} 条`);
    pageData.page = 1;
    pageData.size = val;
    getList();
  }

  function pageCurrentChange(val) {
    console.log(`当前页: ${val}`, pageData);
    pageData.page = val;
    getList();
  }

  function pageSearch() {
    console.log("搜索: ", searchForm);
    pageData.page = 1;
    getList();
  }

  function pageReset() {
    console.log("重置: ", searchForm);
    if (showPage.value) {
      searchFormRef.value.resetFields();
      pageData.page = 1;
      getList();
    }

  }


  function resetForm(row = false) {
    console.log("重置表单: ", searchForm);
    // searchFormRef.value.resetFields();
    if (formRef.value) formRef.value.clearValidate();
    if (row) {
      for (const key in inputForm) {
        inputForm[key] = row[key]
      }
    }
  }

  function edit(type, row) {
    console.log("编辑/详情: ", type, row);
    if (type == 1) {
      modalTitle.value = "新增"
      console.log("新增分类", "category/add");
      // tableRef.value.tbStyle({}, "xxx");
      resetForm({
        uniId: '',
        name: '',//模块名称
        level: 0,//模块等级
        isShow: 1,//状态 0隐藏 1显示
        sort: 0,//排序
        // parentId:0,//父级id
      });

      // Object.assign(this.inputForm, );
      drawerModalRef.value.init();
    } else if (type == 2) {
      modalTitle.value = "编辑"
      resetForm(row);
      // this.inputForm = row;
      drawerModalRef.value.init();
    } else {
      modalTitle.value = "详情"
      getDetail(row.uniId)
    }
    console.log("modalTitle：", modalTitle, "编辑: ", row);


  }

  function del(data) {
    // console.log("删除data: ", data);
    if(data.parentId==0 && data.level==0){
      proxy.$messageInfo.notific.error("顶级分类，不可删除！");
      return

    }
    if(data.children && data.children.length>0){
      proxy.$messageInfo.notific.error("请先删除子分类");
      return 
    }
    api.delete(data.uniId).then(res => {
      if (res.success) {
        proxy.$messageInfo.toast.success("删除成功");
        getList();
      } else {
        proxy.$messageInfo.notific.error("删除失败");
      }
    })
  }

  function changeStatus(row) {
    console.log("修改状态: ", row.isShow);
  }

  onMounted(() => {
    if (showPage.value) {
      getList();
    }

    console.log("页面数据更新开始: ", tableLoading.value);
    console.log("validator-ispc: ", proxy.$validator.isPc());
  });

  return {
    tableLoading,
    tableRef,
    pageData,
    searchForm,
    searchFormRef,
    getList,
    edit,
    del,
    pageSizeChange,
    pageCurrentChange,
    pageSearch,
    pageReset,
    changeStatus,

    drawerModalRef,
    formRef,
    modalTitle,
    saveModal,
    inputForm,
    inputRules,
    formLabelWidth,
    loadingModal,

    showPage,
  }
}